package resource

import "errors"

type Builder struct {
	errs    []error
	visitor Visitor
	items   []VisitorFunc

	continueOnError bool
}

func NewBuilder() *Builder {
	info := &Info{}
	return &Builder{
		visitor: info,
	}
}

func (b *Builder) WithVisitorFunc(fn ...VisitorFunc) *Builder {
	b.items = append(b.items, fn...)
	return b
}

func (b *Builder) visitorResult() *Result {
	if len(b.errs) > 0 {
		return &Result{
			err: errors.Join(b.errs...),
		}
	}
	result := &Result{
		visitor: b.visitor,
	}
	return result
}

func (b *Builder) Do() *Result {
	r := b.visitorResult()
	if r.err != nil {
		return r
	}

	helpers := b.items
	if b.continueOnError {
		r.visitor = ContinueOnErrorVisitor{r.visitor}
	}
	r.visitor = NewDecoratedVisitor(r.visitor, helpers...)
	return r
}
